//引入用户数据库模块
const TestsModel_DB = require("../models/TestsModel_DB")
//引入发送前端工具
const Response = require("../utils/ResponseEntity")
//引入身份凭证插件
const jwt = require("jsonwebtoken")

class TestsController {
    //获取所有类型
    async findAll(req, res, next) {
        try {
            const data = await TestsModel_DB.find()
            if (data.length) res.send(Response.success({ msg: "查询成功", data }))
            else res.send(Response.error({ msg: "查询失败" }))
        } catch (error) {
            console.log(error);
            res.send(Response.error({ msg: "服务器错误" }))
        }
    }
    //获取当前用户未考试卷
    async findNotFinish(req, res, next) {
        try {
            //const token = req.get("Authorization")
            //const { name } = jwt.verify(token.split(" ")[1], "zheshimiyao")
            const data = await TestsModel_DB.find({ form: 1 }).populate("pointId").populate("exercises")
            if (data.length) res.send(Response.success({ data }))
            else res.send(Response.error({ msg: "查询失败" }))
        } catch (error) {
            console.log(error);
            res.send(Response.error({ msg: "服务器错误" }))
        }
    }
    //根据编号获取
    async findById(req, res, next) {
        try {
            const { id } = req.query
            if (id) {
                const data = await TestsModel_DB.findOne({ _id: id }).populate("exercises")
                if (data._id) {
                    res.send(Response.success({ data }))
                } else res.send(Response.error({ msg: "未查询到数据" }))
            } else res.send(Response.error({ msg: "数据不能为空" }))
        } catch (error) {
            console.log(error);
            res.send(Response.error({ msg: "服务器错误" }))
        }
    }

    //修改试卷状态
    async updateTestState(req, res, next) {
        try {
            const { id } = req.query
            const data = await TestsModel_DB.updateOne({ _id: id }, { form: 0 })
            console.log(data);
            if (data.acknowledged == true) 
            res.send(Response.success({msg:"修改成功"}))
            else res,send(Response.error({msg:"修改失败"}))
        } catch (error) {
            console.log(error);
            res.send(Response.error({ msg: "服务器错误" }))
        }
    }
}

const tests = new TestsController()
module.exports = tests